<template>
  <div class="store-add">
    <div class="header">
      <h1>{{ isEdit ? "商品修改" : "商品添加" }}</h1>
      <p>{{ isEdit ? "修改商品" : "添加商品" }}</p>
    </div>
    <div class="body">
      <div class="main">
        <a-steps :current="current" v-show="current < 2">
          <a-step v-for="item in steps" :key="item.title" :title="item.title" />
        </a-steps>
        <div class="steps-content" v-show="current == 0">
          <a-form
            ref="addFormInfo"
            :label-col="labelCol"
            :wrapper-col="wrapperCol"
            :model="addFormInfo"
            :rules="rules"
          >
            <a-form-item label="商品分类" name="proClass">
              <a-cascader
                v-model:value="addFormInfo.proClass"
                :options="options"
                placeholder="请选择分类"
                :fieldNames="fieldNames"
              />
            </a-form-item>
            <a-form-item label="商品名称" name="proName">
              <a-input
                placeholder="请输入商品名称"
                v-model:value="addFormInfo.proName"
              />
            </a-form-item>
            <a-form-item label="商品标题" name="proTitle">
              <a-input
                placeholder="请输入商品标题"
                v-model:value="addFormInfo.proTitle"
              />
            </a-form-item>
            <a-form-item label="商品副标题" name="proSubtitle">
              <a-input
                placeholder="请输入商品副标题"
                v-model:value="addFormInfo.proSubtitle"
              />
            </a-form-item>
            <a-form-item label="进价" name="proCost">
              <a-input
                placeholder="请输入进价"
                v-model:value="addFormInfo.proCost"
              />
            </a-form-item>
            <a-form-item label="售价" name="proPrice">
              <a-input
                placeholder="请输入售价"
                v-model:value="addFormInfo.proPrice"
              />
            </a-form-item>
            <a-form-item label="计价单位" name="proUnit">
              <a-input
                placeholder="请输入计价单位"
                v-model:value="addFormInfo.proUnit"
              />
            </a-form-item>
          </a-form>
        </div>
        <div class="steps-content" v-show="current == 1">
          <a-form
            ref="addFromImg"
            :label-col="labelCol"
            :wrapper-col="wrapperCol"
            :model="addFromImg"
            :rules="rules"
          >
            <a-form-item label="商品封面图" name="proIcon">
              <a-upload
                v-model:fileList="addFromImg.proIcon"
                name="file"
                list-type="picture-card"
                class="avatar-uploader"
                :show-upload-list="false"
                action="http://127.0.0.1:8888/common/upload"
                :before-upload="iconbeforeUpload"
                @change="iconhandleChange"
              >
                <img v-if="iconUrl != ''" :src="iconUrl" alt="avatar" />
                <div v-else>
                  <!-- todo -->
                  <loading-outlined v-if="loading" />
                  <plus-outlined v-else />
                  <div class="ant-upload-text">上传图片</div>
                </div>
              </a-upload>
            </a-form-item>
            <a-form-item label="商品轮播图" name="proImages">
              <a-upload
                action="http://127.0.0.1:8888/common/upload"
                list-type="picture-card"
                v-model:fileList="addFromImg.proImages"
                :before-upload="iconbeforeUpload"
                @preview="handlePreview"
              >
                <div v-if="addFromImg.proImages.length < 4">
                  <plus-outlined />
                  <div class="ant-upload-text">上传图片</div>
                </div>
              </a-upload>
            </a-form-item>
            <a-form-item label="商品详情图片" name="proIntroduction">
              <a-upload
                action="http://127.0.0.1:8888/common/upload"
                list-type="picture-card"
                v-model:fileList="addFromImg.proIntroduction"
                :before-upload="iconbeforeUpload"
                @preview="handlePreview"
              >
                <div>
                  <plus-outlined />
                  <div class="ant-upload-text">上传图片</div>
                </div>
              </a-upload>
            </a-form-item>
          </a-form>
        </div>
        <div v-show="current == 2">
          <a-result
            status="success"
            :title="isEdit ? '商品修改成功' : '商品添加成功'"
            :sub-title="
              isEdit
                ? '商品修改成功'
                : '商品添加成功，但未上架，请到商品列表进行上架操作！'
            "
          >
            <template #extra>
              <a-button
                key="console"
                type="primary"
                @click="goto('Product/ProductList')"
              >
                去商品列表</a-button
              >
            </template>
          </a-result>
        </div>
        <div v-show="current == 3">
          <a-result
            status="error"
            :title="isEdit ? '商品修改失败' : '商品添加失败'"
            :sub-title="isEdit ? '商品修改失败' : '商品添加失败 返回重新添加！'"
          >
            <template #extra>
              <a-button key="console" type="primary" @click="current = 0">
                {{ isEdit ? "重新修改" : "重新添加" }}</a-button
              >
            </template>
          </a-result>
        </div>
      </div>
      <div class="operation">
        <a-button v-show="current == 1" @click="prev(1)">
          上一步,填写商品信息</a-button
        >

        <a-button
          type="primary"
          style="margin-left: 10px"
          v-show="current == 0"
          @click="next(0)"
          >下一步,填写商品展示</a-button
        >
        <a-button
          type="primary"
          style="margin-left: 10px"
          v-show="current == 1"
          @click="next(1)"
          >完成，提交商品</a-button
        >
      </div>
    </div>
    <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
      <img alt="example" style="width: 100%" :src="previewImage" />
    </a-modal>
    <a-modal
      v-model:visible="visible"
      :footer="null"
      :closable="false"
      :maskClosable="false"
    >
      <a-result :title="isEdit ? '正在修改' : '正在添加'">
        <template #icon>
          <LoadingOutlined />
        </template>
      </a-result>
    </a-modal>
  </div>
</template>

<script>
import { PlusOutlined, LoadingOutlined } from "@ant-design/icons-vue";
import { message } from "ant-design-vue";

export default {
  components: {
    PlusOutlined,
    LoadingOutlined,
  },
  data() {
    return {
      labelCol: { span: 4 },
      wrapperCol: { span: 14 },
      current: 0,
      isEdit: false,
      iconUrl: "",
      //配置步骤条
      steps: [
        {
          title: "填写商品信息",
        },
        {
          title: "商品展示信息",
        },
      ],
      visible: false,
      fieldNames: {
        label: "className",
        value: "classId",
        children: "children",
      },

      options: [],
      //上传图片 轮播图
      previewVisible: false,
      previewImage: "",

      loading: false,

      //添加表单
      addFormInfo: {
        proId: "",
        storeId: "",
        proName: "", //商品名
        proClass: [], //商品类型id
        proTitle: "", //商品标题
        proSubtitle: "", //商品副标题
        proUnit: "", //单位
        proPrice: "", //价格
        proCost: "", //进价
      },
      addFromImg: {
        proIntroduction: [], //详情图
        proImages: [], //轮播图片
        proIcon: [], //封面图
      },
      rules: {
        proName: [
          {
            required: true,
            message: "请输入商品名",
            trigger: "blur",
          },
        ],
        proClass: [
          {
            type: "array",
            required: true,
            message: "请选择商品类型",
            trigger: "blur",
          },
        ],
        proTitle: [
          {
            required: true,
            message: "请输入商品标题",
            trigger: "blur",
          },
        ],
        proSubtitle: [
          {
            required: true,
            message: "请输入商品副标题",
            trigger: "blur",
          },
        ],
        proUnit: [
          {
            required: true,
            message: "请输入商品单位",
            trigger: "blur",
          },
        ],
        proPrice: [
          {
            required: true,
            message: "请输入商品价格",
            trigger: "blur",
          },
        ],
        proCost: [
          {
            required: true,
            message: "请输入商品进价",
            trigger: "blur",
          },
        ],

        proIcon: [
          {
            type: "array",
            required: true,
            message: "请上传封面图",
            trigger: "blur",
          },
        ],
        proImages: [
          {
            type: "array",
            required: true,
            message: "请上传轮播图",
            trigger: "blur",
          },
        ],
        proIntroduction: [
          {
            type: "array",
            required: true,
            message: "请上传详情图",
            trigger: "blur",
          },
        ],
      },
    };
  },
  activated() {
    this.init();
  },
  mounted() {
    this.getData();
  },
  methods: {
    init() {
      if (this.$route.params.proInfo != undefined) {
        this.isEdit = true;
        let proInfo = JSON.parse(this.$route.params.proInfo);
        console.log(proInfo);
      
        this.addFormInfo.proName = proInfo.proName;
        this.addFormInfo.proClass = [
          proInfo.proClass.substring(0, 1) + "0000",
          proInfo.proClass,
        ];
        this.addFormInfo.proTitle = proInfo.proTitle;
        this.addFormInfo.proSubtitle = proInfo.proSubtitle;
        this.addFormInfo.proUnit = proInfo.proUnit;
        this.addFormInfo.proPrice = proInfo.proPrice + "";
        this.addFormInfo.proCost = proInfo.proCost + "";
        this.addFormInfo.proId = proInfo.proId;
        this.addFormInfo.isDiscount=proInfo.isDiscount;

        this.addFormInfo.storeId=proInfo.storeId;
        this.addFormInfo.proDis=proInfo.proDis;

        let proIntroductionArr = proInfo.proIntroduction.split(",");
        this.addFromImg.proIntroduction = [];
        for (let index = 0; index < proIntroductionArr.length; index++) {
          const element = proIntroductionArr[index];
          this.addFromImg.proIntroduction.push({
            uid: "-" + (index + 1),
            name: "image.png",
            status: "done",
            url: element,
            response: {
              data: {
                url: element,
              },
            },
          });
        }

        let proImagesArr = proInfo.proImages.split(",");
        this.addFromImg.proImages = [];
        for (let index = 0; index < proImagesArr.length; index++) {
          const element = proImagesArr[index];
          this.addFromImg.proImages.push({
            uid: "-" + (index + 1),
            name: "image.png",
            status: "done",
            url: element,
            response: {
              data: {
                url: element,
              },
            },
          });
        }
        let proIconArr = proInfo.proIcon.split(",");
        this.addFromImg.proIcon = [];
        for (let index = 0; index < proIconArr.length; index++) {
          const element = proIconArr[index];
          this.addFromImg.proIcon.push({
            uid: "-" + (index + 1),
            name: "image.png",
            status: "done",
            url: element,
            response: {
              data: {
                url: element,
              },
            },
          });
        }

        this.iconUrl = proIconArr[0];
        console.log(this.addFormInfo);
      } else {
        this.isEdit = false;
        (this.addFormInfo = {
          proId: "",
          storeId: "",
          proName: "", //商品名
          proClass: [], //商品类型id
          proTitle: "", //商品标题
          proSubtitle: "", //商品副标题
          proUnit: "", //单位
          proPrice: "", //价格
          proCost: "", //进价
        }),
          (this.addFromImg = {
            proIntroduction: [], //详情图
            proImages: [], //轮播图片
            proIcon: [], //封面图
          });
        this.iconUrl = "";
      }
    },
    next(index) {
      if (index == 0) {
        this.$refs.addFormInfo
          .validate()
          .then(() => {
            this.current = 1;
          })
          .catch((error) => {
            console.log("error", error);
          });
      } else if (index == 1) {
        this.$refs.addFromImg
          .validate()
          .then(() => {
            this.visible = true;
            let proIntroduction = "";
            let proImages = "";
            for (
              let index = 0;
              index < this.addFromImg.proIntroduction.length;
              index++
            ) {
              const element = this.addFromImg.proIntroduction[index];
              proIntroduction =
                proIntroduction + "," + element.response.data.url;
            }
            for (
              let index = 0;
              index < this.addFromImg.proImages.length;
              index++
            ) {
              const element = this.addFromImg.proImages[index];
              proImages = proImages + "," + element.response.data.url;
            }

            proIntroduction = proIntroduction.substring(
              1,
              proIntroduction.length
            );
            proImages = proImages.substring(1, proImages.length);
            if (this.isEdit) {
              this.$axios
                .post("/admin/product/edit", {
                  proId: this.addFormInfo.proId,
                  storeId: this.addFormInfo.storeId,
                  proName: this.addFormInfo.proName,
                  proClass: this.addFormInfo.proClass[1],
                  proTitle: this.addFormInfo.proTitle,
                  proSubtitle: this.addFormInfo.proSubtitle,
                  proUnit: this.addFormInfo.proUnit,
                  proPrice: this.addFormInfo.proPrice,
                  proCost: this.addFormInfo.proCost,
                  proIntroduction: proIntroduction,
                  proImages: proImages,
                  proIcon: this.addFromImg.proIcon[0].response.data.url,
                  proDis:this.addFormInfo.proDis,
                  isDiscount:this.addFormInfo.isDiscount
                })
                .then((res) => {
                  this.visible = false;
                  if (res.data.code == 2000) {
                    this.current = 2;
                  } else {
                    this.current = 3;
                  }
                })
                .catch((error) => {
                  this.current = 3;
                  this.visible = false;
                });
            } else {
              this.$axios
                .post("/admin/product/add", {
                  proName: this.addFormInfo.proName,
                  proClass: this.addFormInfo.proClass[1],
                  proTitle: this.addFormInfo.proTitle,
                  proSubtitle: this.addFormInfo.proSubtitle,
                  proUnit: this.addFormInfo.proUnit,
                  proPrice: this.addFormInfo.proPrice,
                  proCost: this.addFormInfo.proCost,
                  proIntroduction: proIntroduction,
                  proImages: proImages,
                  proIcon: this.addFromImg.proIcon[0].response.data.url,
                })
                .then((res) => {
                  this.visible = false;
                  if (res.data.code == 2000) {
                    this.current = 2;
                  } else {
                    this.current = 3;
                  }
                })
                .catch((error) => {
                  this.current = 3;
                  this.visible = false;
                });
            }
          })
          .catch((error) => {
            console.log("error", error);
          });
      }
    },
    prev(index) {
      if (index == 0) {
      } else if (index == 1) {
        this.current = 0;
      }
    },
    getData() {
      this.$axios.get("admin/classification/all").then((res) => {
        this.options = res.data.data;
      });
    },

    //路由跳转
    goto(path) {
      this.current = 0;
      this.$router.push("/home/" + path);
    },
    //轮播图 ========================
    handleCancel() {
      this.previewVisible = false;
    },
    async handlePreview(file) {
      this.previewImage = file.response.data.url;
      this.previewVisible = true;
    },

    //封面图 =======================
    iconhandleChange(info) {
      if (info.file.status === "uploading") {
        this.loading = true;
        return;
      }
      if (info.file.status === "done") {
        // Get this url from response in real world.
        this.iconUrl = info.file.response.data.url;
        this.loading = false;
        message.success("上传成功");
      }
      if (info.file.status === "error") {
        this.loading = false;
        message.error("上传失败");
      }
    },
    iconbeforeUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        message.error("图片尺寸不能超过2M ！");
      }
      return isLt2M;
    },
  },
};
</script>

<style lang="less" scoped>
.store-add .header {
  background-color: #fff;
  padding: 24px;
}
.store-add .header h1 {
  color: rgba(0, 0, 0, 0.85);
  font-weight: 600;
  font-size: 20px;
  line-height: 32px;
}
.store-add .body {
  padding: 24px;
  background-color: #fff;
  margin: 24px 16px;
  display: flex;
  justify-content: center;
  flex-direction: column;
  align-items: center;
}
.store-add .body .main {
  width: 70%;
}
.steps-content {
  margin-top: 16px;
}
.operation {
  display: flex;
  justify-content: center;
}
</style>